package com.fare.taluo.core.domain.analyse.report.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.fare.taluo.core.domain.analyse.report.CsairTaobaoEntity;
import com.fare.taluo.core.domain.analyse.report.CsairTaobaoEntityRepository;
import com.fare.taluo.fetl.domain.base.EntityFetlHibernateRepository;
import com.fare.taluo.util.DateUtils;
import com.fare.taluo.util.StringAndDateAndFileUtil;

@Repository("csairTaobaoEntityRepository")
public class CsairTaobaoEntityRepositoryImpl extends
		EntityFetlHibernateRepository implements CsairTaobaoEntityRepository {
	
	@SuppressWarnings("unchecked")
	@Override
	public List<CsairTaobaoEntity> findByCondition(String fromCity,
			String toCity, String flightNo, String flightDate,String reportDate) {
		try {
			List<Object> params = new ArrayList<Object>();
			String sbf = "from com.fare.taluo.core.domain.analyse.report.CsairTaobaoEntity fm where 1=1";
			if (StringAndDateAndFileUtil.checkString(fromCity)) {
				sbf += " and fm.fromCity = ?";
				params.add(fromCity);
			}
			if (StringAndDateAndFileUtil.checkString(toCity)) {
				sbf += " and fm.toCity = ?";
				params.add(toCity);
			}
			if (StringAndDateAndFileUtil.checkString(flightNo)) {
				sbf += " and fm.flightNo = ?";
				params.add(flightNo);
			}
			if (StringAndDateAndFileUtil.checkString(flightDate)) {
				sbf += " and fm.flightDate = ?";
				params.add(DateUtils.parseDate(flightDate, "yyyy-MM-dd"));
			}
			if(StringAndDateAndFileUtil.checkString(reportDate)){
				sbf += " and fm.reportDate = ?";
				params.add(DateUtils.parseDate(reportDate, "yyyy-MM-dd"));
			}
			sbf += " order by fm.fromCity, fm.toCity,fm.channelKey";
			Session session = getSessionFactory1().openSession();
			List<CsairTaobaoEntity> list = null;
			try {
				Query query = session.createQuery(sbf);
				//System.out.println(session.getSessionFactory().toString());
				for (int i = 0; i < params.size(); i++) {
					query = query.setParameter(i, params.get(i));
				}
				list = query.list();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				session.close();
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
